package org.qydjk.console.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.qydjk.common.controller.BaseController;
import org.qydjk.common.pojo.user.User;
import org.qydjk.common.pojo.user.UserAccount;
import org.qydjk.common.util.BeanUtil;
import org.qydjk.common.util.StringUtil;
import org.qydjk.common.vo.EasyUIResponse;
import org.qydjk.common.vo.HibernatePage;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Lanan on 2017/12/18 0018.
 */

@Controller
@RequestMapping("/user/account")
public class UserAccountController extends BaseController {
    @RequestMapping("/index.do")
    public String userAccount() {
        return "user/account/userAccount";
    }

    @RequestMapping("/list.do")
    @ResponseBody
    public Object userAccountList(int page, int rows) {
        List<UserAccount> userAccounts = new ArrayList<UserAccount>();
        Integer total = 0;
        String sql = "SELECT * FROM qy_user_account WHERE 1 = 1";
        String countSql = "SELECT COUNT(id) FROM qy_user_account WHERE 1 = 1";

        sql += addSearchWhereString();
        countSql += addSearchWhereString();

        sql += " order by update_time desc";
        try {
            userAccounts = baseService.findBySQL(sql, UserAccount.class, new HibernatePage(page, rows));
            total = baseService.getRecordCountSQL(countSql);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new EasyUIResponse(total, userAccounts);
    }

    /**
     * 添加搜素时的条件
     * @return 条件字符串
     */
    private String addSearchWhereString() {
        String whereStr = "";

        String userId = request.getParameter("userId");
        String account = request.getParameter("account");
        String type = request.getParameter("type");
        if (!StringUtil.isEmptyOrNull(userId)) {
            whereStr += " and user_id = " + userId;
        }
        if (!StringUtil.isEmptyOrNull(account)) {
            whereStr += " and (wechat_account like '%" + account + "%'" +
                        " or ali_account like '%" + account + "%'" +
                        " or bank_account like '%" + account + "%')";
        }
        if (!StringUtil.isEmptyOrNull(type)) {
            whereStr += " and type = " + type;
        }
        return whereStr;
    }

    @RequestMapping("/insert/index.do")
    public String insertIndex() {
        return "user/account/userAccountInsert";
    }

    @RequestMapping("/update/index.do")
    public String updateIndex(Model model, Integer id) {
        try {
            UserAccount userAccount = baseService.get(UserAccount.class, id);
            model.addAttribute("userAccount", userAccount);
            return "user/account/userAccountUpdate";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/update.do")
    @ResponseBody
    public Object updateUserAccount(UserAccount userAccount) {
        return handleSaveOrUpdate(false, userAccount, "修改");
    }

    @RequestMapping("/insert.do")
    @ResponseBody
    public Object insertUserAccount(UserAccount userAccount) {
        try {
            User user = baseService.get(User.class, userAccount.getUserId());
            userAccount.setName(user.getUsername());
            userAccount.setPhone(user.getPhone());
            return handleSaveOrUpdate(true, userAccount, "添加");
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject resp = new JSONObject();
        resp.put("success", false);
        resp.put("msg", "操作错误");
        return JSON.toJSON(resp);
    }

    /**
     * 保存和修改的处理
     * @param isSave true:添加 false:修改
     * @param userAccount 前端提交的数据
     * @param msg 后端给前端的提示信息
     * @return 返回数据
     */
    private Object handleSaveOrUpdate(Boolean isSave, UserAccount userAccount, String msg) {
        if (userAccount.getType() == 0) { // 银行卡
            userAccount.setWechatAccount("");
            userAccount.setAliAccount("");
        } else {
            userAccount.setBankAccount("");
            userAccount.setBankName("");
            userAccount.setBankOpening("");
            if (userAccount.getType() == 1) { // 支付宝
                userAccount.setWechatAccount("");
            } else if (userAccount.getType() == 2) { // 微信
                userAccount.setAliAccount("");
            }
        }
        JSONObject resp = new JSONObject();
        if (userAccount.getUserId() == null) {
            resp.put("success", false);
            resp.put("msg", "用户不存在或操作错误！");
        } else {
            try {
                // 如果该用户已有该类卡账户
                if (theUserAccountHasUse(userAccount)) {
                    resp.put("success", false);
                    if (isSave) resp.put("msg", "用户" + userAccount.getName() + "下此账号已存在，添加失败");
                    else resp.put("msg", "该用户下此账号已存在，修改失败！");
                    return JSON.toJSON(resp);
                }
                if (userAccount.getDef() != null && userAccount.getDef() == 1) {
                    String sql = "update qy_user_account " +
                            "set def = '0' " +
                            "where def = '1' " +
                            "and user_id = " + userAccount.getUserId();
                    baseService.excuteSQL(sql);
                }
                if (isSave) userAccount.setCreateTime(new Date());
                userAccount.setUpdateTime(new Date());
                if (isSave) {
                    baseService.save(userAccount);
                } else {
                    UserAccount uda = baseService.get(UserAccount.class, userAccount.getId());
                    BeanUtil.copyProperties(userAccount, uda);
                    baseService.update(uda);
                }
                resp.put("success", true);
                resp.put("msg", msg);
            } catch (Exception e) {
                e.printStackTrace();
                resp.put("success", false);
                resp.put("msg", e.toString());
            }
        }
        return JSON.toJSON(resp);
    }

    /**
     * 判断该用户是否拥有当前操作账号
     * @param userAccount 前端提交数据
     * @return true:已有  false:没有
     */
    private boolean theUserAccountHasUse(UserAccount userAccount) {
        String sql = "select id from qy_user_account where user_id = " + userAccount.getUserId();
        Integer id = null;
        // 如果是银行卡
        if (userAccount.getType() == 0) {
            sql += " and bank_account = '" + userAccount.getBankAccount() + "'";
        } else if (userAccount.getType() == 1) {
            // 如果是支付宝
            sql += " and ali_account = '" + userAccount.getAliAccount()+"'";
        } else if (userAccount.getType() == 2) {
            // 如果是微信
            sql += " and wechat_account = '" + userAccount.getWechatAccount() + "'";
        }
        try {
            id = baseService.getUniqueResultSQL(sql);
        } catch (Exception e) {
            e.printStackTrace();
            return true;
        }
        if (id == null || id == userAccount.getId()) {
            return false;
        }
        return true;
    }

    @RequestMapping("/delete.do")
    @ResponseBody
    public Object deleteUserAccount(UserAccount userAccount) {
        JSONObject resp = new JSONObject();
        Integer id = userAccount.getId();
        if(id == null || id == 0){
            resp.put("success", false);
            resp.put("msg", "id不能为空！");
        } else {
            try {
                resp.put("success", true);
                baseService.delete(userAccount);
            } catch (Exception e) {
                resp.put("success", false);
                resp.put("msg", e.toString());
            }
        }
        return JSON.toJSON(resp);
    }
}
